import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera'
import { Engine } from '@babylonjs/core/Engines/engine'
import { Color3, Color4, Vector3 } from '@babylonjs/core/Maths'
import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'
import { Scene } from '@babylonjs/core/scene'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

// import { Inspector } from "@babylonjs/inspector";

export default function useInitBabylon(
  container: Ref<HTMLCanvasElement | null>
) {
  const engine = ref<Engine | null>(null)
  const scene = ref<Scene | null>(null)
  const camera = ref<ArcRotateCamera | null>(null)

  onMounted(async () => {
    // 初始化引擎与场景
    engine.value = new Engine(container.value, true)
    // 创建场景
    scene.value = new Scene(engine.value as Engine)
    scene.value.clearColor = new Color4(0, 0, 0, 0) // RGBA(0,0,0,0)表示完全透明
    scene.value.ambientColor = new Color3(0.5, 0.5, 0.5) // 环境光
    // scene.value.fogMode = Scene.FOGMODE_EXP; // 雾效
    createCamera()
    // createPhysics(scene.value as Scene)
    // createAxis(scene.value as Scene); // 创建坐标轴

    // 确保场景准备就绪
    // scene.value.executeWhenReady(() => {
    //      //  调试工具
    //     Inspector.Show(scene.value as Scene, {
    //         embedMode: true
    //     });
    // })

    window.addEventListener('resize', () => engine.value?.resize())
  })

  onUnmounted(() => {
    window.removeEventListener('resize', () => engine.value?.resize())
    camera.value?.detachControl() // 解绑事件
    camera.value?.inputs.clear() // 清理自定义输入
    scene.value?.materials.forEach((mat) => mat.dispose())
    scene.value?.textures.forEach((tex) => tex.dispose())
    scene.value?.meshes.forEach((mesh) => mesh.dispose())
    scene.value?.dispose()
    engine.value?.dispose()
  })

  // 相机
  const createCamera = () => {
    // 创建相机
    camera.value = new ArcRotateCamera(
      'camera',
      Math.PI / 2,
      Math.PI / 2.5,
      60,
      new Vector3(0, 0, 0),
      scene.value as Scene
    )
    camera.value.lowerRadiusLimit = 10 // 最小缩放距离
    camera.value.upperRadiusLimit = 60 // 最大缩放距离

    camera.value.zoomToMouseLocation = true // 启用鼠标缩放
    camera.value.wheelDeltaPercentage = 0.1 // 鼠标滚轮缩放速度

    // 设置相机的 alpha 和 beta 限制
    // 这里的 alpha 和 beta 是弧度制，范围是 [0, 2 * Math.PI]
    // camera.value.lowerAlphaLimit = Math.PI / 4; // 45°
    // camera.value.upperAlphaLimit = 3 * Math.PI / 4; // 135°
    camera.value.lowerBetaLimit = Math.PI / 3
    camera.value.upperBetaLimit = Math.PI / 2.5

    // 启用惯性
    camera.value.inertia = 0.5 // 惯性值，范围是 [0, 1]，值越大，惯性越强
    camera.value.attachControl(container.value, true)

    camera.value.storeState() // 保存当前状态为初始状态
    // 恢复初始视角
    // camera.value?.restoreState();

    // console.log("camera", scene.value.useRightHandedSystem);
  }

  // 物理引擎
  // const createPhysics = (scene:Scene) => {
  //     const gravity = new Vector3(0, -9.81, 0); // 定义重力
  //     const physicsPlugin = new CannonJSPlugin(); // 使用CannonJS作为物理引擎
  //     scene.enablePhysics(gravity, physicsPlugin); // 激活物理引擎
  // }

  // 坐标
  const createAxis = (scene: Scene) => {
    // X轴（红色）
    MeshBuilder.CreateLines(
      'axisX',
      {
        points: [Vector3.Zero(), new Vector3(10, 0, 0)],
        // colors: [new Color4(1, 1, 1, 1), new Color4(1, 0, 0, 1)] // 起点白色，终点红色
        colors: [new Color4(1, 0, 0, 1), new Color4(1, 0, 0, 1)], // 起点白色，终点红色
      },
      scene
    )

    // Y轴（绿色）
    MeshBuilder.CreateLines(
      'axisY',
      {
        points: [Vector3.Zero(), new Vector3(0, 10, 0)],
        colors: [new Color4(0, 1, 0, 1), new Color4(0, 1, 0, 1)],
      },
      scene
    )

    // Z轴（蓝色）
    MeshBuilder.CreateLines(
      'axisZ',
      {
        points: [Vector3.Zero(), new Vector3(0, 0, 10)],
        colors: [new Color4(0, 0, 1, 1), new Color4(0, 0, 1, 1)],
      },
      scene
    )
  }

  return { engine, scene, camera }
}
